package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.domain.vo.NearUserVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.RecommendUserVo;
import com.itheima.domain.vo.VisitorVo;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @Reference //dubbo
    RecommendUserService recommendUserService;

    @Reference
    UserInfoService userInfoService;

    @Reference
    QuestionService questionService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Reference
    VisitorService visitorService;

    @Reference
    UserLocationService userLocationService;

    public ResponseEntity findTodayBest() {
        //1.获取登陆用户id
        Long userId = UserHolder.get().getId();

        //2.调用service查询当前用户的最佳
        RecommendUser recommendUser = recommendUserService.findTodayBest(userId);
        //2.1 若是新用户,没有推荐用户的,自己new一个
        if (recommendUser == null) {
            recommendUser = new RecommendUser();

            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);
        }

        //3.获取推荐者的userInfo
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

        //4.封装vo且返回
        RecommendUserVo recommendUserVo = new RecommendUserVo();

        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(recommendUserVo);
    }

    public ResponseEntity findRecommendUserByPage(int pageNum, int pageSize) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.调用service查询推荐好友分页数据
        PageBeanVo page = recommendUserService.findByPage(pageNum, pageSize, userId);

        //3.获取推荐好友集合,遍历集合,获取每个好友的userInfo,封装成vo对象,放入新集合中
        //3.0 创建RecommendUserVoList
        List<RecommendUserVo> recommendUserVoList = new ArrayList<>();

        //3.1 获取推荐好友集合
        List<RecommendUser> items = (List<RecommendUser>) page.getItems();

        //3.2 判断集合是否为空(新用户为空,new一些出来)
        if (CollUtil.isEmpty(items)) {// 注意  注意  注意
            for (int i = 0; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();

                recommendUser.setUserId(2L + i);
                recommendUser.setScore(98D - i);

                items.add(recommendUser);
            }

            page.setCounts(10L);
        }

        //3.3 遍历集合,获取每个好友userInfo
        for (RecommendUser recommendUser : items) {
            UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

            //3.4 封装成vo对象
            RecommendUserVo recommendUserVo = new RecommendUserVo();

            recommendUserVo.setUserInfo(userInfo);
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());

            //3.5 放入voList中
            recommendUserVoList.add(recommendUserVo);
        }



        //4.返回新集合,放入page中
        page.setItems(recommendUserVoList);

        return ResponseEntity.ok(page);
    }

    public ResponseEntity findRecommendUserPersonal(Long recommendUserId) {
        //1.调用service查询推荐用户(可能没有)
        RecommendUser recommendUser = recommendUserService.findPersonal(recommendUserId, UserHolder.get().getId());
        if (recommendUser == null) {
            recommendUser = new RecommendUser();

            recommendUser.setScore(RandomUtil.randomDouble(60,99));
        }

        //2.获取推荐用户id,查询userInfo
        UserInfo userInfo = userInfoService.findById(recommendUserId);

        //3.封装推荐用户vo对象
        RecommendUserVo recommendUserVo = new RecommendUserVo();

        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        //4.返回
        return ResponseEntity.ok(recommendUserVo);
    }

    public ResponseEntity findStrangerQuestion(Long userId) {
        //1.调用QuestionService查询问题
        Question question = questionService.findByUserId(userId);

        //2.判断是否为空,若为空设置默认值
        if (question == null) {
            return ResponseEntity.ok("你是喜欢渣男，还是暗恋靓女？？");
        }
        //3.返回陌生人问题
        return ResponseEntity.ok(question.getStrangerQuestion());
    }

    public ResponseEntity findVisitorsSinceLastAccessTime() {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.从redis中获取上次登陆时间,且保存当次访问时间
        String lastTimeStr = stringRedisTemplate.opsForValue().getAndSet(ConstantUtil.LAST_ACCESS_TIME + userId,System.currentTimeMillis()+"");

        //3.判断是否是第一次访问,设置上次登陆时间的默认值0
        Long lastAccessTime = NumberUtil.isLong(lastTimeStr)?NumberUtil.parseLong(lastTimeStr):0;

        //4.调用service查询访问的用户列表
        List<Visitor> visitors = visitorService.findVisitorsSinceLastAccessTime(userId, lastAccessTime);

        //5.若列表不为空,遍历列表,获取每个访客userInfo
        //5.1 创建VisitorVoList
        List<VisitorVo> visitorVoList = new ArrayList<>();

        //5.2 遍历访客列表
        if (CollUtil.isNotEmpty(visitors)) {
            for (Visitor visitor : visitors) {
                //5.3 获取每个访客userInfo
                UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());

                //5.4 封装访客vo,且放入集合中
                VisitorVo visitorVo = new VisitorVo();

                visitorVo.setUserInfo(userInfo);
                visitorVo.setFateValue(visitor.getScore().longValue());

                visitorVoList.add(visitorVo);
            }
        }

        //6 返回
        return ResponseEntity.ok(visitorVoList);
    }

    public ResponseEntity saveUserLocation(double longitude, double latitude, String address) {
        //1.获取当前用户的id
        //2.调用service完成保存操作
        userLocationService.saveOrUpdate(UserHolder.get().getId(),longitude,latitude,address);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity searchNear(String gender, int distance) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.调用service查询附近的人(只需要id)
        List<Long> ids = userLocationService.searchNear(userId, distance);

        //3.遍历集合,获取每人UserInfo,封装成NearUserVo,把vo放入集合中
        //3.1 创建NearUserVoList
        List<NearUserVo> nearUserVoList = new ArrayList<>();

        //3.2 遍历集合,获取用户userInfo
        if (CollUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                UserInfo userInfo = userInfoService.findById(id);

                //3.3 判断性别是否为指定性别,若是则封装vo
                if (!StrUtil.equals(userInfo.getGender(),gender)) {
                    continue;
                }

                NearUserVo nearUserVo = new NearUserVo();

                nearUserVo.setUserId(id);
                nearUserVo.setNickname(userInfo.getNickname());
                nearUserVo.setAvatar(userInfo.getAvatar());

                //3.4 将vo放入list中
                nearUserVoList.add(nearUserVo);
            }
        }
        //4.返回
        return ResponseEntity.ok(nearUserVoList);
    }
}
